package com.example.project3.util;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class API<T> {

    private T result;
    private boolean success = true;
    private int serviceCode;
    private String errorMessage = "";
    @Deprecated
    private String errorDetail = "";

    public API(T result) {
        this.result = result;
    }

    public API() {
    }

    @Deprecated
    public static API<String> failed(String message, String errorDetail) {
        API<String> api = new API<>("error");
        api.setSuccess(false);
        api.setServiceCode(-1);
        api.setErrorMessage(message);
        api.setErrorDetail(errorDetail);
        return api;
    }

    public static API<String> failed(String message) {
        API<String> api = new API<>("error");
        api.setSuccess(false);
        api.setServiceCode(-1);
        api.setErrorMessage(message);
        api.setErrorDetail(message);
        return api;
    }

    public static <T> API<T> success(T result) {
        API<T> api = new API<>(result);
        return api;
    }

    public static <T> API<Boolean> success() {
        API<Boolean> api = new API<Boolean>(true);
        return api;
    }

    public T getResult() {
        return result;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public int getServiceCode() {
        return serviceCode;
    }

    public void setServiceCode(int serviceCode) {
        this.serviceCode = serviceCode;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    public String getErrorDetail() {
        return errorDetail;
    }

    public void setErrorDetail(String errorDetail) {
        this.errorDetail = errorDetail;
    }

    @Override
    public String toString() {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(this);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("conversion json failed", e);
        }
    }
}
